package com.yfree.utils;

import android.text.TextUtils;
import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class YGZipUtils {
    private static final String charsetName = "UTF-8";

    public static String compress(String input) {
        if (TextUtils.isEmpty(input)) {
            return "";
        }
        String result = "";
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                    input.getBytes());
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            GZIPOutputStream gos = new GZIPOutputStream(byteArrayOutputStream);
            byte data[] = new byte[1024];
            int count;
            while ((count = byteArrayInputStream.read(data, 0, data.length)) != -1) {
                gos.write(data, 0, count);
            }
            gos.flush();
            gos.finish();
            gos.close();
            byteArrayInputStream.close();
            result = URLEncoder.encode(Base64.encodeToString(
                    byteArrayOutputStream.toByteArray(), Base64.DEFAULT),
                    charsetName);
            byteArrayOutputStream.flush();
            byteArrayOutputStream.close();
        } catch (Exception ignored) {
        }
        return result;
    }

    public static String deCompress(String inBase64) {
        if (TextUtils.isEmpty(inBase64)) {
            return "";
        }
        String result = "";
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                    Base64.decode(URLDecoder.decode(inBase64, charsetName),
                            Base64.DEFAULT));
            GZIPInputStream gzipInputStream = new GZIPInputStream(
                    byteArrayInputStream);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte data[] = new byte[1024];
            int count;
            while ((count = gzipInputStream.read(data, 0, data.length)) != -1) {
                byteArrayOutputStream.write(data, 0, count);
            }
            gzipInputStream.close();
            byteArrayInputStream.close();
            result = new String(byteArrayOutputStream.toByteArray());
            byteArrayOutputStream.flush();
            byteArrayOutputStream.close();
        } catch (Exception ignored) {
        }
        return result;
    }
}
